<template>
  <el-dialog
    :model-value="projectDialogStore.isOpen"
    :title="projectDialogStore.mode === 'create' ? '新建项目' : '编辑项目'"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
    class="project-dialog"
  >
    <div v-loading="projectDialogStore.loading" class="dialog-content">
      <!-- 步骤导航 -->
      <el-steps
        :active="projectDialogStore.currentStep"
        finish-status="success"
        align-center
        class="form-steps"
      >
        <el-step
          v-for="(step, index) in projectDialogStore.steps"
          :key="step.id"
          :title="step.title"
          :description="step.description"
        />
      </el-steps>

      <!-- 步骤内容 -->
      <div class="steps-content">
        <!-- 基本信息 -->
        <div v-show="projectDialogStore.currentStep === 0" class="step-panel">
          <el-form
            ref="basicFormRef"
            :model="projectDialogStore.formData"
            :rules="basicFormRules"
            label-width="120px"
            label-position="left"
          >
            <el-form-item label="项目名称" prop="name">
              <el-input
                v-model="projectDialogStore.formData.name"
                placeholder="请输入项目名称"
                maxlength="100"
                show-word-limit
                clearable
              />
              <div v-if="projectDialogStore.errors.name" class="form-error">
                {{ projectDialogStore.errors.name }}
              </div>
            </el-form-item>

            <el-form-item label="项目描述" prop="description">
              <el-input
                v-model="projectDialogStore.formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入项目描述"
                maxlength="1000"
                show-word-limit
                clearable
              />
              <div v-if="projectDialogStore.errors.description" class="form-error">
                {{ projectDialogStore.errors.description }}
              </div>
            </el-form-item>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="项目类型" prop="project_type">
                  <el-select
                    v-model="projectDialogStore.formData.project_type"
                    placeholder="请选择项目类型"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="type in projectDialogStore.typeOptions"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                    >
                      <span>{{ type.label }}</span>
                      <span class="option-desc">{{ type.description }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="项目状态" prop="status">
                  <el-select
                    v-model="projectDialogStore.formData.status"
                    placeholder="请选择项目状态"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="status in projectStatusOptions"
                      :key="status.value"
                      :label="status.label"
                      :value="status.value"
                    >
                      <span style="display: flex; align-items: center; gap: 8px">
                        <el-tag :type="(status.type || 'info') as 'success' | 'primary' | 'warning' | 'info' | 'danger'" size="small">
                          {{ status.label }}
                        </el-tag>
                        <span class="option-desc" v-if="status.description">{{ status.description }}</span>
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="优先级" prop="priority">
                  <el-select
                    v-model="projectDialogStore.formData.priority"
                    placeholder="请选择优先级"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="priority in projectDialogStore.priorityOptions"
                      :key="priority.value"
                      :label="priority.label"
                      :value="priority.value"
                    >
                      <span style="display: flex; align-items: center; gap: 8px">
                        <el-tag :type="(priority.type || 'info') as 'success' | 'primary' | 'warning' | 'info' | 'danger'" size="small">
                          {{ priority.label }}
                        </el-tag>
                        <span class="option-desc">{{ priority.description }}</span>
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="是否公开" prop="is_public">
                  <el-switch
                    v-model="projectDialogStore.formData.is_public"
                    active-text="公开"
                    inactive-text="私有"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 详细配置 -->
        <div v-show="projectDialogStore.currentStep === 1" class="step-panel">
          <el-form
            ref="detailsFormRef"
            :model="projectDialogStore.formData"
            :rules="detailsFormRules"
            label-width="120px"
            label-position="left"
          >
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="开始日期" prop="start_date">
                  <el-date-picker
                    v-model="projectDialogStore.formData.start_date"
                    type="date"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                    clearable
                  />
                  <div v-if="projectDialogStore.errors.start_date" class="form-error">
                    {{ projectDialogStore.errors.start_date }}
                  </div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="结束日期" prop="end_date">
                  <el-date-picker
                    v-model="projectDialogStore.formData.end_date"
                    type="date"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                    clearable
                    :disabled-date="(date: Date) => {
                      if (projectDialogStore.formData.start_date) {
                        return date < new Date(projectDialogStore.formData.start_date)
                      }
                      return false
                    }"
                  />
                  <div v-if="projectDialogStore.errors.end_date" class="form-error">
                    {{ projectDialogStore.errors.end_date }}
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="预算" prop="budget">
              <el-input-number
                v-model="projectDialogStore.formData.budget"
                :min="0"
                :precision="2"
                placeholder="请输入预算金额"
                style="width: 100%"
              />
              <div v-if="projectDialogStore.errors.budget" class="form-error">
                {{ projectDialogStore.errors.budget }}
              </div>
            </el-form-item>

            <el-form-item label="代码仓库URL" prop="repository_url">
              <el-input
                v-model="projectDialogStore.formData.repository_url"
                placeholder="请输入代码仓库URL，如：https://github.com/user/repo"
                clearable
              />
              <div v-if="projectDialogStore.errors.repository_url" class="form-error">
                {{ projectDialogStore.errors.repository_url }}
              </div>
            </el-form-item>

            <el-form-item label="文档URL" prop="documentation_url">
              <el-input
                v-model="projectDialogStore.formData.documentation_url"
                placeholder="请输入文档URL"
                clearable
              />
              <div v-if="projectDialogStore.errors.documentation_url" class="form-error">
                {{ projectDialogStore.errors.documentation_url }}
              </div>
            </el-form-item>

            <el-form-item label="标签">
              <el-select
                v-model="projectDialogStore.formData.tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="输入标签并回车添加"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in commonTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 确认信息 -->
        <div v-show="projectDialogStore.currentStep === 2" class="step-panel">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="项目名称">
              {{ projectDialogStore.formData.name }}
            </el-descriptions-item>
            <el-descriptions-item label="项目类型">
              {{ getTypeLabel(projectDialogStore.formData.project_type) }}
            </el-descriptions-item>
            <el-descriptions-item label="项目状态">
              <el-tag :type="getStatusType(projectDialogStore.formData.status)" size="small">
                {{ getStatusLabel(projectDialogStore.formData.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(projectDialogStore.formData.priority)" size="small">
                {{ getPriorityLabel(projectDialogStore.formData.priority) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="开始日期">
              {{ projectDialogStore.formData.start_date || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="结束日期">
              {{ projectDialogStore.formData.end_date || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="预算">
              {{ projectDialogStore.formData.budget ? `¥${projectDialogStore.formData.budget.toLocaleString()}` : '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="是否公开">
              {{ projectDialogStore.formData.is_public ? '公开' : '私有' }}
            </el-descriptions-item>
            <el-descriptions-item label="项目描述" :span="2">
              {{ projectDialogStore.formData.description || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="代码仓库" :span="2">
              {{ projectDialogStore.formData.repository_url || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="文档URL" :span="2">
              {{ projectDialogStore.formData.documentation_url || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="标签" :span="2">
              <el-tag
                v-for="tag in projectDialogStore.formData.tags"
                :key="tag"
                size="small"
                style="margin-right: 8px"
              >
                {{ tag }}
              </el-tag>
              <span v-if="projectDialogStore.formData.tags.length === 0">无标签</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          v-if="projectDialogStore.currentStep > 0"
          @click="handlePrevious"
        >
          上一步
        </el-button>
        <el-button
          v-if="projectDialogStore.currentStep < projectDialogStore.steps.length - 1"
          type="primary"
          @click="handleNext"
          :loading="projectDialogStore.loading"
        >
          下一步
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="handleSubmit"
          :loading="projectDialogStore.loading"
        >
          {{ projectDialogStore.mode === 'create' ? '创建' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useProjectDialogStore } from '@/stores/projectDialog'
import { useProjectStates } from '@/composables/useProjectStates'
import type { ProjectStatus, ProjectPriority, ProjectType } from '@/api/project'

// Props
interface Props {
  // 可以添加 props
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  (e: 'success'): void
}>()

// Store
const projectDialogStore = useProjectDialogStore()

// 状态选项
const { statusOptions: projectStatusOptionsRaw, loadStates: loadProjectStates } = useProjectStates()

// 加载状态选项
onMounted(() => {
  loadProjectStates()
})

// 格式化状态选项
const projectStatusOptions = computed(() => {
  return projectStatusOptionsRaw.value.map(status => ({
    value: status.value as ProjectStatus,
    label: status.label,
    type: status.type || 'info',
    description: status.description
  }))
})

// 常用标签
const commonTags = ref<string[]>([
  '前端', '后端', '移动端', '桌面端', 'API', '数据库',
  'UI/UX', '测试', '文档', '部署', '运维', '安全'
])

// 表单引用
const basicFormRef = ref()
const detailsFormRef = ref()

// 表单验证规则
const basicFormRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 1, max: 100, message: '项目名称长度在1到100个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: '项目描述不能超过1000个字符', trigger: 'blur' }
  ],
  project_type: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

const detailsFormRules = {
  budget: [
    { type: 'number', min: 0, message: '预算不能为负数', trigger: 'blur' }
  ],
  repository_url: [
    { pattern: /^https?:\/\/.+/, message: '请输入有效的URL', trigger: 'blur', required: false }
  ],
  documentation_url: [
    { pattern: /^https?:\/\/.+/, message: '请输入有效的URL', trigger: 'blur', required: false }
  ]
}

// 处理关闭
const handleClose = () => {
  projectDialogStore.closeDialog()
}

// 处理上一步
const handlePrevious = () => {
  if (projectDialogStore.currentStep > 0) {
    projectDialogStore.setCurrentStep(projectDialogStore.currentStep - 1)
  }
}

// 处理下一步
const handleNext = async () => {
  // 验证当前步骤
  let isValid = true
  if (projectDialogStore.currentStep === 0) {
    if (basicFormRef.value) {
      try {
        await basicFormRef.value.validate()
        isValid = projectDialogStore.validateForm(0)
      } catch {
        isValid = false
      }
    }
  } else if (projectDialogStore.currentStep === 1) {
    if (detailsFormRef.value) {
      try {
        await detailsFormRef.value.validate()
        isValid = projectDialogStore.validateForm(1)
      } catch {
        isValid = false
      }
    }
  }

  if (isValid && projectDialogStore.currentStep < projectDialogStore.steps.length - 1) {
    projectDialogStore.setCurrentStep(projectDialogStore.currentStep + 1)
  }
}

// 处理提交
const handleSubmit = async () => {
  // 验证所有步骤
  let isValid = true
  if (basicFormRef.value) {
    try {
      await basicFormRef.value.validate()
      isValid = projectDialogStore.validateForm(0)
    } catch {
      isValid = false
    }
  }

  if (detailsFormRef.value) {
    try {
      await detailsFormRef.value.validate()
      isValid = isValid && projectDialogStore.validateForm(1)
    } catch {
      isValid = false
    }
  }

  if (!isValid) {
    // 回到第一个有错误的步骤
    if (projectDialogStore.currentStep !== 0 && Object.keys(projectDialogStore.errors).length > 0) {
      projectDialogStore.setCurrentStep(0)
    }
    return
  }

  // 提交表单
  const success = await projectDialogStore.submitForm()
  if (success) {
    emit('success')
  }
}

// 辅助函数：获取类型标签
const getTypeLabel = (type: ProjectType) => {
  const typeOption = projectDialogStore.typeOptions.find(opt => opt.value === type)
  return typeOption?.label || type
}

// 辅助函数：获取状态标签
const getStatusLabel = (status: ProjectStatus) => {
  const statusOption = projectStatusOptions.value.find(opt => opt.value === status)
  return statusOption?.label || status
}

// 辅助函数：获取状态类型
const getStatusType = (status: ProjectStatus): 'success' | 'info' | 'warning' | 'danger' | 'primary' => {
  const statusOption = projectStatusOptions.value.find(opt => opt.value === status)
  const type = statusOption?.type || 'info'
  // 确保返回的是有效的Element Plus tag type
  if (type === 'success' || type === 'info' || type === 'warning' || type === 'danger' || type === 'primary') {
    return type
  }
  return 'info'
}

// 辅助函数：获取优先级标签
const getPriorityLabel = (priority: ProjectPriority) => {
  const priorityOption = projectDialogStore.priorityOptions.find(opt => opt.value === priority)
  return priorityOption?.label || priority
}

// 辅助函数：获取优先级类型
const getPriorityType = (priority: ProjectPriority): 'success' | 'info' | 'warning' | 'danger' | 'primary' => {
  const priorityOption = projectDialogStore.priorityOptions.find(opt => opt.value === priority)
  const type = priorityOption?.type || 'info'
  // 确保返回的是有效的Element Plus tag type
  if (type === 'success' || type === 'info' || type === 'warning' || type === 'danger' || type === 'primary') {
    return type
  }
  return 'info'
}
</script>

<style scoped lang="scss">
.project-dialog {
  .dialog-content {
    min-height: 400px;
    padding: 20px 0;
  }

  .form-steps {
    margin-bottom: 30px;
  }

  .steps-content {
    min-height: 300px;
  }

  .step-panel {
    padding: 20px 0;
  }

  .form-error {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
  }

  .option-desc {
    color: #909399;
    font-size: 12px;
    margin-left: 8px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
